package com.pinxixi.goods.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pinxixi.framework.domain.brand.Brand;
import com.pinxixi.framework.domain.category.Category;
import com.pinxixi.framework.domain.goods.Goods;
import com.pinxixi.framework.domain.goods.GoodsDesc;
import com.pinxixi.framework.domain.goods.Item;
import com.pinxixi.framework.domain.goods.ext.GoodsEntity;
import com.pinxixi.framework.model.response.*;
import com.pinxixi.goods.client.BrandApiClient;
import com.pinxixi.goods.client.CategoryApiClient;
import com.pinxixi.goods.mapper.GoodsMapper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;

@Service
public class GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private BrandApiClient brandApiClient;

    @Autowired
    private CategoryApiClient categoryApiClient;

    @Autowired
    private RedisTemplate redisTemplate;

    public ResponseResult save(GoodsEntity goodsEntity) {
        if(goodsEntity.getGoods().getId()==null){
            Goods goods = goodsEntity.getGoods();
            goodsMapper.addGoods(goods);

            GoodsDesc goodsDesc = goodsEntity.getGoodsDesc();
            goodsDesc.setGoodsId(goods.getId());
            goodsMapper.addGoodsDesc(goodsDesc);

            QueryResponseResult<Brand> brandResponse = brandApiClient.findOne(goods.getBrandId());
            QueryResponseResult<Category> categoryResponse = categoryApiClient.findOne(goods.getCategory3Id());

            //品牌名称 + 商品名称 + 规格值
            String title_pre = brandResponse.getEntity().getName()+ " "+goods.getGoodsName();

            String itemImages = goodsDesc.getItemImages();
            List<Map> list = JSONArray.parseArray(itemImages, Map.class);
            String imageUrl = (String) list.get(0).get("url");

            List<Item> items = goodsEntity.getItem();
            for(Item item : items){
                item.setGoodsId(goods.getId());
                String spec = item.getSpec();
                Map specMap = JSONObject.parseObject(spec, Map.class);
                Iterator iterator = specMap.keySet().iterator();

                String title = title_pre;
                while (iterator.hasNext()){
                    String key = (String) iterator.next();
                    Object value = specMap.get(key);
                    title += " "+value;
                }
                item.setTitle(title);
                item.setCategoryid(goods.getCategory3Id());
                item.setBrand(brandResponse.getEntity().getName());
                item.setCategory(categoryResponse.getEntity().getName());
                item.setImage(imageUrl);
                goodsMapper.addItem(item);
            }

        }else{

        }
        return ResponseResult.SUCCESS();
    }

    public ListResponseResult<Goods> findPage() {
        List<Goods> list = goodsMapper.findPage();
        QueryResult<Goods> queryResult = new QueryResult<>();
        queryResult.setList(list);
        return new ListResponseResult<Goods>(CommonCode.SUCCESS,queryResult);
    }

    public ResponseResult commitApply(Long[] ids) {
        goodsMapper.commitApply(ids);
        return ResponseResult.SUCCESS();
    }

    public ResponseResult goodsApply(Long[] ids, Integer status) throws Exception {
        Map map = new HashMap();
        map.put("ids",ids);
        map.put("status",status);
        goodsMapper.goodsApply(map);

        //判断当前用户是  通过？驳回？

        if(status==2){
            this.initHTML(ids);
        }

        return ResponseResult.SUCCESS();
    }

    private void initHTML(Long[] ids) throws Exception {
        for(Long id : ids){
            //每一个id对应一个SPU    一个SPU对应多个SKU   每个SKU需要一个HTML
            //根据商品ID  查询 tb_goods  tb_goods_desc   tb_item--->List
            Goods goods = goodsMapper.findGoods(id);
            GoodsDesc goodsDesc = goodsMapper.findGoodsDesc(id);
            List<Item> itemList = goodsMapper.findItemByGoodsId(id);

            //遍历得到每个SKU---》item
            for(Item item : itemList){
                //数据 + 模版 = HTML
                Map map = new HashMap();
                map.put("goods",goods);
                map.put("goodsDesc",goodsDesc);
                map.put("item",item);
                map.put("itemList",JSONArray.toJSONString(itemList));

                Configuration configuration = new Configuration(Configuration.getVersion());
                String path = this.getClass().getResource("/").getPath()+"freemarker";
                System.out.println(path);

                configuration.setDefaultEncoding("UTF-8");

                configuration.setDirectoryForTemplateLoading(new File(path));
                Template template = configuration.getTemplate("item.ftl");

                String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);

                InputStream inputStream = IOUtils.toInputStream(html, "UTF-8");
                FileOutputStream outputStream = new FileOutputStream("/Users/zhengyi/work/pinxixi-portal-web/html/" + item.getId() + ".html");

                IOUtils.copy(inputStream,outputStream);

            }

        }
    }

    public QueryResponseResult findOne(Long id) {
        GoodsEntity goodsEntity = new GoodsEntity();
        Goods goods = goodsMapper.findGoods(id);
        GoodsDesc goodsDesc = goodsMapper.findGoodsDesc(id);
        List<Item> itemList = goodsMapper.findItemByGoodsId(id);
        goodsEntity.setGoods(goods);
        goodsEntity.setGoodsDesc(goodsDesc);
        goodsEntity.setItem(itemList);
        return new QueryResponseResult(CommonCode.SUCCESS,goodsEntity);
    }


    /**
     *  hash
     *  key                     hashKey     value
     *  spu+spuid             skuid       price&num
     *  spu149187842867972    1369284     {num:50,price:6666}
     *                        1369285     {num:50,price:6666}
     *                        1369286     {num:50,price:6666}
     *                         ....
     */

    public QueryResponseResult goodsCache(Long spuid,Long skuid) {
        Map map = redisTemplate.opsForHash().entries("spu" + spuid);
        if(map.isEmpty()){
            List<Item> itemList = goodsMapper.findItemByGoodsId(spuid);
            for(Item item:itemList){
                Map cache = new HashMap();
                cache.put("num",item.getNum());
                cache.put("price",item.getPrice());
                map.put(item.getId(),cache);
            }
            redisTemplate.opsForHash().putAll("spu"+spuid,map);
        }
        return new QueryResponseResult(CommonCode.SUCCESS,map);
    }
}
